import { provide, inject, reactive, createApp, h, toRefs } from "vue";
import Pop from './pop.vue'
const PopSymbol = Symbol();

const state = reactive({
    show: false, // pop元素是否显示
    option: {
        text: '', //文案
        cancelBtn: true,
        cancelText: '取消',
        okBtn: true,
        okLoading: false,
        okLoadingText: '加载中',
        okText: '确认',
        ok: () => { },
        cancel: () => { },
        close: () => {
            _pop.close();
        }
    },
});

let [popVM, popWrapper] = [null, null, null];

const _pop = (opt) => {
    state.show = true;
    if (!opt.text) {
        return;
    }
    state.option.text = opt.text;
    state.option.cancelText = opt.cancelText || '取消';
    state.option.okText = opt.okText || '确认';
    state.option.okLoadingText = opt.okLoadingText || '加载中';
    if (opt.cancelBtn === false) {
        state.option.cancelBtn = opt.cancelBtn;
    } else {
        state.option.cancelBtn = true;
    }
    if (opt.okBtn == false) {
        state.option.okBtn = opt.okBtn;
    } else {
        state.option.okBtn = true;
    }
    if (opt.cancel) {
        state.option.cancel = () => {
            opt.cancel();
            _pop.close();
        }
    } else {
        state.option.cancel = () => {
            _pop.close();
        }
    }
    if (opt.ok) {
        state.option.ok = () => {
            const re = opt.ok();
            if (re === undefined) {
                _pop.close();
            } else if (re === false) {
                state.option.okLoading = true;
            } else if (re === true) {
                _pop.close();
            }
            return re;
        }
    } else {
        state.option.ok = () => {
            _pop.close();
        }
    }
    if (!popVM) {
        // 如果pop实例存在则不重新创建
        popVM = createApp(Pop, toRefs(state));
    }

    if (!popWrapper) {
        // 如果该节点以经存在则不重新创建
        popWrapper = document.createElement("div");
        popWrapper.id = "sf-pop";
        document.body.appendChild(popWrapper);
        popVM.mount("#sf-pop");
    }
};
_pop.close = () => {
    state.show = false;
    state.option.okLoading = false;
}

export function providePop(config = {}) {
    for (const key in config) {
        globalConfig[key] = config[key];
    }
    provide(PopSymbol, _pop);
}

export function usePop() {
    const pop = inject(PopSymbol);
    if (!pop) {
        throw new Error("error");
    }
    return pop;
}